package main

import (
	"fmt"
	"os"
	"os/exec"
)

func main() {
	fileIn, err := os.Open("input.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}

	in := make([]byte, 100000)
	out := make([]byte, 100000)
	_, err = fileIn.Read(in)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	//test1
	cmd := exec.Command("bash", "-c", "$GOPATH/bin/selpg -s10 -e20 input.txt >output.txt")
	err = cmd.Run()
	if err != nil {
		fmt.Println(err)
		os.Exit(2)
	}

	fileOut, err := os.Open("output.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(3)
	}

	_, err = fileOut.Read(out)
	if err != nil {
		fmt.Println(err)
		os.Exit(4)
	}

	iIn := 0
	iOut := 0
	page := 1
	line := 0
	for ; page < 10; page++ {
		for ; line < 72; iIn++ {
			if in[iIn] == '\n' {
				line++
			}
		}
		line = 0
	}
	for ; page <= 20; page++ {
		for ; line < 72; iIn++ {
			if in[iIn] != out[iOut] {
				fmt.Println("Failed in test1: selpg -s10 -e20 input.txt >output.txt")
				os.Exit(5)
			}
			iOut++
			if in[iIn] == '\n' {
				line++
			}
		}
		line = 0
	}

	//test2:-f
	cmd = exec.Command("bash", "-c", "$GOPATH/bin/selpg -s1 -e1 -f input.txt >output.txt")
	err = cmd.Run()
	if err != nil {
		fmt.Println(err)
		os.Exit(6)
	}

	fileOut, err = os.Open("output.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(7)
	}

	_, err = fileOut.Read(out)
	if err != nil {
		fmt.Println(err)
		os.Exit(8)
	}

	for i := 0; i < len(in); i++ {
		if in[i] != out[i] {
			fmt.Println("Failed in test2: selpg -s1 -e1 -f input.txt >output.txt")
			os.Exit(9)
		}
		if in[i] == '\f' {
			break
		}
	}

	//test3:-l
	cmd = exec.Command("bash", "-c", "$GOPATH/bin/selpg -s10 -e20 -l66 input.txt >output.txt")
	err = cmd.Run()
	if err != nil {
		fmt.Println(err)
		os.Exit(10)
	}

	fileOut, err = os.Open("output.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(11)
	}

	_, err = fileOut.Read(out)
	if err != nil {
		fmt.Println(err)
		os.Exit(12)
	}

	iIn = 0
	iOut = 0
	page = 1
	line = 0
	for ; page < 10; page++ {
		for ; line < 66; iIn++ {
			if in[iIn] == '\n' {
				line++
			}
		}
		line = 0
	}
	for ; page <= 20; page++ {
		for ; line < 66; iIn++ {
			if in[iIn] != out[iOut] {
				fmt.Println("Failed in test3: selpg -s10 -e20 -l66 input.txt >output.txt")
				os.Exit(13)
			}
			iOut++
			if in[iIn] == '\n' {
				line++
			}
		}
		line = 0
	}

	fmt.Println("All tests passed")
}
